package com.atguigu.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.common.util.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author fan
 * @since 2021-11-22
 */
@Slf4j
@RestController
@RequestMapping("/admin/core/dict")

@Api(tags = "数据字典管理")
public class AdminDictController {
    @Autowired
    private DictService dictService;
    @ApiOperation("字典列表显示")
    @GetMapping("/listByParentId/{parentId}")
    public R listByParentId(@PathVariable("parentId") Long parentId){
        List<Dict> listDick = dictService.listDick(parentId);
        return R.ok().data("listDick",listDick);
    }
    @ApiOperation("Excel导入")
    @PostMapping("/import")
    public R importsData( @ApiParam(value = "Excel文件", required = true) @RequestParam("file") MultipartFile multipartFile){
        boolean b = dictService.importData(multipartFile);
        Assert.isTrue(b, ResponseEnum.ERROR);
        return R.ok();
    }
    @SneakyThrows
    @GetMapping("/export")
    @ApiOperation("Excel导出")
    public void exportData(HttpServletResponse response){
        response.setContentType("application/vnd.ms-excel");
        String fileName = URLEncoder.encode("尚融宝业务字典信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        response.setCharacterEncoding("utf-8");
        //创建一个ExcelDictDTO类型的集合，用于等下装数据库读出来的excel表数据
        List<ExcelDictDTO> excelDictDTOS = new ArrayList<>();
        //调用service的list方法获取数据库中的excel表数据
        List<Dict> excelDict = dictService.list();
        //遍历集合

        for (Dict dict : excelDict) {
            //new一个ExcelDictDTO对象用于装遍历出来的每一行数据
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            //把dict中的数据填到excelDictDTO中
            BeanUtils.copyProperties(dict,excelDictDTO);
            //
            excelDictDTOS.add(excelDictDTO);
        }
        EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("数据字典").doWrite(excelDictDTOS);
    }
}

